package com.gf.user.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gf.base.type.Activity;
import com.gf.base.type.LicenseState;
import com.gf.base.type.Role;
import com.gf.base.type.SafeFactor;
import com.gf.common.bean.Page;
import com.gf.common.constant.Constants;
import com.gf.common.constant.ViewPaths;
import com.gf.common.util.MailHelper;
import com.gf.common.util.UuidHelper;
import com.gf.common.util.WebHelper;
import com.gf.user.dao.UserBaseDao;
import com.gf.user.model.Ticket;
import com.gf.user.model.User;
import com.gf.user.service.TicketService;
import com.gf.user.service.UserBaseService;

@Transactional
@Service("userBaseService")
public class UserBaseServiceImpl implements UserBaseService {

	private static Log logger = LogFactory.getLog(UserBaseServiceImpl.class);

	// springconfig.properties
	@Value("${domain.name}")
	private String domainName;

	// springconfig.properties
	@Value("${base.name}")
	private String baseName;

	@Autowired
	private UserBaseDao userBaseDao;

	@Autowired
	private TicketService ticketService;

	/**
	 * 注册
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public long register(String nickname, String email, String password,
			String idNumber, String realName, String sex, String role,
			String major, String safeFactor) {
		String ip = WebHelper.getClientIp(null);
		// 转化为MD5
		// password = MessageDigester.getDigester().strToMD5(password);
		return userBaseDao.insert(UuidHelper.generateUuid(), nickname, email,
				password, idNumber, realName, null, null, sex, role, ip, major,
				SafeFactor.valueOf(safeFactor));

	}

	/**
	 * 通过邮箱登入
	 */
	@Override
	public User loginByEmail(String email, String password) {
		// 转化为MD5
		// password = MessageDigester.getDigester().strToMD5(password);
		return userBaseDao.queryByEmail(email, password);
	}

	/**
	 * 通过身份证号登入
	 */
	@Override
	public User loginByID(String idNumber, String password) {
		// 转化为MD5
		// password = MessageDigester.getDigester().strToMD5(password);
		return userBaseDao.queryByIdNumber(idNumber, password);
	}

	/**
	 * 找回密码，并返回修改密码的URL 时间有效性为24小时
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public String findPasswdReturnWithUrl(String email, String idNumber) {
		User user = userBaseDao.queryEmailIdNumberExist(email, idNumber);
		if (user != null) {
			String uuid = UuidHelper.generateUuid();
			// 通过验证返回URL
			String url = "http://" + domainName + "/" + baseName
					+ ViewPaths.MODIFYFORGETPASSWD_VIEW + ViewPaths.SUFFIX
					+ "?uuid=" + uuid;

			String content = "找回密码,请猛击下面的链接:<br>" + "<a href='" + url + "'>"
					+ url + "</a><br>" + new Date();

			// 写入数据库ticket.sql
			long id = ticketService.addFindPasswdTicket(user.getId(),
					uuid.toString());
			Ticket ticket = ticketService.getTicket(id);
			// 从session中
			WebHelper.setSessionAttribute(null,
					Constants.SESSION_FIND_PASSWD_TICKET, ticket);

			try {
				MailHelper.sendHtmlMail(email, "用户找回密码", content);
			} catch (Exception e) {
				logger.info("找回密码：" + email + " 发送失败");
				ticketService.deleteTicket(ticket.getId());// 回滚
				WebHelper.removeSessionAttribute(null,
						Constants.SESSION_FIND_PASSWD_TICKET);
				return "";
			}
			logger.info("找回密码：" + email + " 发送成功");

			return url;
		} else {
			return "";
		}
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public void modifyPasswd(long id, String newPasswd) {
		// 转化为MD5
		// newPasswd = MessageDigester.getDigester().strToMD5(newPasswd);
		userBaseDao.updatePasswd(id, newPasswd);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public String activeUserReturnWithUrl(String email, String idNumber) {

		User user = userBaseDao.queryEmailIdNumberExist(email, idNumber);
		if (user != null) {
			String uuid = UuidHelper.generateUuid();
			// 通过验证返回URL
			String url = "http://" + domainName + "/" + baseName
					+ ViewPaths.ACTIVE_VIEW + ViewPaths.SUFFIX + "?uuid="
					+ uuid;

			String content = "激活帐号,请猛击下面的链接:<br>" + "<a href='" + url + "'>"
					+ url + "</a><br>" + new Date();

			// 写入数据库ticket.sql
			long id = ticketService.addActiveTicket(user.getId(),
					uuid.toString());
			Ticket ticket = ticketService.getTicket(id);
			// 储存到session中
			WebHelper.setSessionAttribute(Constants.SESSION_ACTIVE_USER_TICKET,
					ticket);

			try {// 发送邮件
				MailHelper.sendHtmlMail(email, "激活帐号", content);
			} catch (Exception e) {
				logger.error("用户注册：" + user.getEmail() + " 发送邮件出错!");

				userBaseDao.deleteUser(user.getId());
				ticketService.deleteTicket(ticket.getId());// 回滚
				WebHelper.removeSessionAttribute(null,
						Constants.SESSION_ACTIVE_USER_TICKET);
				return "";
			}
			logger.error("向用户注册：" + user.getEmail() + " 发送邮件成功!");
			return url;
		} else {
			return "";
		}

	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public void activeUser(long id) {
		User user = getUserById(id);
		// 病人（也就是普通用户）
		if (user.getRole().toString().equals(Role.NORMAL.toString())) {
			if (!user.getActivity().toString()
					.equals(Activity.NORMAL.toString())) {
				userBaseDao.updateActivity(id, Activity.NORMAL);
			}
		}
		// 医生 在执照通过验证之前 部分功能被冻结:不能发布项目
		else if (user.getRole().toString().equals(Role.DOCTOR.toString())) {
			if (!user.getActivity().toString()
					.equals(Activity.NORMAL.toString())) {
				userBaseDao.updateActivity(id, Activity.NORMAL);
			}
		}

	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public void deleteUser(long id) {
		userBaseDao.deleteUser(id);
	}

	@Override
	public User isUserExist(String email) {
		return userBaseDao.queryEmailExist(email);
	}

	@Override
	public User getUserById(long id) {
		return userBaseDao.queryUserById(id);
	}

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public boolean passCheckingOfDoctor(long id, LicenseState licenseState) {
		return userBaseDao.updateLicenseState(id, licenseState);
	}

	@Override
	public boolean isNicknameExist(String nickname) {
		User user = userBaseDao.queryUserByNickname(nickname);
		if (user != null) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Page getAllBaseUsers(int currentPage, int pageSize, Role role) {
		List<User> users = userBaseDao.queryAllBaseUsers(currentPage, pageSize,
				role);
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);
		int total = userBaseDao.queryAllBaseUserNumber(role);
		page.setTotal(total);
		page.setResults(users);
		return page;
	}

	@Override
	public Page getAllUsers(int currentPage, int pageSize) {
		List<User> users = userBaseDao.queryAllUsers(currentPage, pageSize);
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);
		int total = userBaseDao.queryAllUserNumber();
		page.setTotal(total);
		page.setResults(users);
		return page;
	}

	@Override
	public String getAboutContent() {
		return userBaseDao.queryAboutContent();
	}

	@Override
	public User getLatestUser() {

		return userBaseDao.queryLatestUser();
	}

}
